$(function(){
    $("#openLoadModal").on("click",function(){
        DownLoadTemplate.openLoadModal();
    });

    //报告期年份更新指标体系
    $("#report_time_option").on("change",function (e) {
        var year = $("#report_time_option  option:selected").val();
        if(year!=""&&year!=null){
            DownLoadTemplate.getIndex(year);
        }
    });

    //指标体系选择事件
    $("#target_check_index").on("change",function () {
        var id = $("#target_check_index  option:selected").val();
        if(id!=""&&id!=null){
            DownLoadTemplate.getAllIndex(id);
        }
    });

    //下载模板按钮点击
    $("#downLoadTemplate").on("click",function () {
        DownLoadTemplate.downLoadTemplate();
    });

    //添加文件
    $("#add-file").click(function () {
        $("#files").click();
    });
    //重置文件选择
    $("#reset-file").click(function () {
        $("#files").val('');
        $("div.reset-list").html('');
    });
    //上传按钮事件
    $("#upload-btn").click(function () {
        UpLoadTemplate.init();
    });
    //显示选择的文件
    $("#files").change(function () {
        var files = $("#files").get(0).files;
        var item = "";
        for (var i = 0; i < files.length; i++) {
            item += "<div class=\"item\">" + files[i].name + "</div>";
        }
        $("div.reset-list").html(item);
    });

    //上传模板按钮事件
    $(".upload_file").on("click",function () {
        UpLoadTemplate.uploadTemplate();
    })

    //上传模板年份改变事件
    $("#uploadTemplate_Modal .report_time_option").on("change",function (e) {
        var year = $("#uploadTemplate_Modal .report_time_option  option:selected").val();
        if(year!=""&&year!=null){
            GetData.getIndex(year,function (data) {
                UpLoadTemplate.initIndex(data);
            });
        }
    });

})

//下载
var DownLoadTemplate = {};
//打开下载导入模板弹窗
DownLoadTemplate.openLoadModal =  function(){
    $('#downLoadTemplate_Modal').modal('show');
    DownLoadTemplate.findHasReportYears();
};
//查询有报告期的年份
DownLoadTemplate.findHasReportYears = function () {
    var url = window.login_url.base_page_url+"/target/find/years";
    $.ajax({
        type: "GET",
        url: url,
        dataType: "json",
        success: function(re){
            if(re.years.length>0){
                var years = re.years;
                var html = '';
                for(var i = 0; i < years.length; i++){
                    var item = '<option value="'+years[i]+'">'+years[i]+'</option>';
                    html += item;
                }
                $("#report_time_option").empty();
                $("#report_time_option").html(html);
            }else{
                console.log('没有报告期年份');
            }
        },
        error:function (re) {
            console.log(re);
        }
    });
};
//根据年份选择指标体系
DownLoadTemplate.getIndex =  function (year) {
    var url = window.login_url.base_page_url+"/target/getComboBox";
    $.ajax({
        type: "GET",
        url: url,
        dataType: "json",
        data:{
            year:year
        },
        success: function(re){
            if(re.length>0){
                var html = '';
                for(var i = 0; i < re.length; i++){
                    var item = '<option value="'+re[i].id+'" data-code="'+re[i].code+'">'+re[i].name+'</option>';
                    html += item;
                }
                $("#target_check_index").empty();
                $("#target_check_index").html(html);

                DownLoadTemplate.getAllIndex();
            }else{
                console.log('没有指标体系');
            }
        },
        error:function (re) {
            console.log(re);
        }
    });
};
//获取指标体系下所有指标
DownLoadTemplate.getAllIndex = function () {
    var id = $("#target_check_index  option:selected").val();
    if(id!=""&&id!=null){
        $(".index-child-list").empty();//清空指标字段
        GetData.getAllIndex(id,function (data) {
            DownLoadTemplate.initAllIndex(data);
        });
    }
};
//渲染所有指标
DownLoadTemplate.initAllIndex = function (data) {
    var html= '';
    for(var i = 0; i < data.length; i++){
        if(data[i].name){
            var item = '<div class="item">'+
                '<div class="ui child checkbox">'+
                '<input type="checkbox" name="allIndexCheckbox"  data-indexname="'+data[i].name+'" value="'+data[i].zb_code+'"/>'+
                '<label>'+data[i].name+'</label>'+
                '</div>'+
                '</div>';
            html += item;
        }
    }
    $(".index-child-list").html(html);
    DownLoadTemplate.initCheckboxAllIndex();
};
//初始化所有指标的多选功能
DownLoadTemplate.initCheckboxAllIndex = function () {
    $('.index-list.list .master.checkbox')
        .checkbox({
        // check all children
        onChecked: function() {
            var
                $childCheckbox  = $(this).closest('.checkbox').siblings('.list').find('.checkbox')
            ;
            $childCheckbox.checkbox('check');
        },
        // uncheck all children
        onUnchecked: function() {
            var
                $childCheckbox  = $(this).closest('.checkbox').siblings('.list').find('.checkbox')
            ;
            $childCheckbox.checkbox('uncheck');
        }
    })
    ;
    $('.index-child-list.list .child.checkbox')
        .checkbox({
            // Fire on load to set parent value
            fireOnInit : true,
            // Change parent state on each child checkbox change
            onChange   : function() {
                var
                    $listGroup      = $(this).closest('.list'),
                    $parentCheckbox = $listGroup.closest('.item').children('.checkbox'),
                    $checkbox       = $listGroup.find('.checkbox'),
                    allChecked      = true,
                    allUnchecked    = true
                ;
                // check to see if all other siblings are checked or unchecked
                $checkbox.each(function() {
                    if( $(this).checkbox('is checked') ) {
                        allUnchecked = false;
                    }
                    else {
                        allChecked = false;
                    }
                });
                // set parent checkbox state, but dont trigger its onChange callback
                if(allChecked) {
                    $parentCheckbox.checkbox('set checked');
                }
                else if(allUnchecked) {
                    $parentCheckbox.checkbox('set unchecked');
                }
                else {
                    $parentCheckbox.checkbox('set indeterminate');
                }
            }
        })
    ;
};
//下载模板功能
DownLoadTemplate.downLoadTemplate = function () {
    var arr = []; //定义一个数组
    $('input[name="allIndexCheckbox"]:checked').each(function() {
        arr.push({
            indexCode:$(this).val(),
            indexName:$(this).attr("data-indexname")
        });
    });

    var year = $("#report_time_option  option:selected").val();
    var month = $("#report_time_month_option option:selected").val();
    var sysCode = $("#target_check_index option:selected").attr('data-code');
    var url = window.login_url.base_page_url+"target/excel/download";
    var time = year+month;

    var json = JSON.stringify({
        "time":time,
        "codes":arr,
        "sysCode":sysCode
    });

    $.ajax({
        type: "POST",
        url: url,
        dataType: "json",
        contentType: "application/json",
        data:json,
        success: function(re){
            alert("下载模板成功");
        },
        error:function (re) {
            console.log(re);
        }
    });
    var twoUrl = window.login_url.base_page_url+"target/downFile";
    SGIS.Util.downloadData("download_iframe",twoUrl);
};


//数据获取
var GetData = {}
//获取有报告期的年份
GetData.getReportTime = function (callback) {
    var data = [];
    var url = window.login_url.base_page_url+"/target/find/years";
    $.ajax({
        type: "GET",
        url: url,
        dataType: "json",
        success: function(re){
            if(re.years.length>0){
                data =  re.years;
                callback && callback(data);
            }else{
                console.log('没有报告期年份');
            }
        },
        error:function (re) {
            console.log(re);
        }
    });
};
//根据报告期年份选择指标体系
GetData.getIndex =  function (year,callback) {
    var url = window.login_url.base_page_url+"/target/getComboBox";
    $.ajax({
        type: "GET",
        url: url,
        dataType: "json",
        data:{
            year:year
        },
        success: function(re){
            if(re.length>0){
                callback && callback(re);
            }else{
                console.log('没有指标体系');
            }
        },
        error:function (re) {
            console.log(re);
        }
    });
};

GetData.getAllIndex = function (id,callback) {
    var url = window.login_url.base_page_url+"/target/all/indexCol/by/sysCode";
    $.ajax({
        type: "GET",
        url: url,
        dataType: "json",
        data:{
            sysId:id
        },
        success: function(re){
            if(re.length>0){
                callback&&callback(re);
            }else{
                console.log('没有查到指标');
            }
        },
        error:function (re) {
            console.log(re);
        }
    });
}


//上传模板方法类
var UpLoadTemplate = {};
//初始化上传功能
UpLoadTemplate.init = function () {
    UpLoadTemplate.openUpLoadTemplate();
    GetData.getReportTime(function (reportTime) {
        UpLoadTemplate.initReportTime(reportTime);
    });
}
//打开上传模板窗口
UpLoadTemplate.openUpLoadTemplate =  function () {
    $('#uploadTemplate_Modal').modal('show');

}
//初始化报告期
UpLoadTemplate.initReportTime = function (reportTime) {
    var years = reportTime;
    var html = '';
    for(var i = 0; i < years.length; i++){
        var item = '<option value="'+years[i]+'">'+years[i]+'</option>';
        html += item;
    }
    $("#uploadTemplate_Modal .report_time_option").empty();
    $("#uploadTemplate_Modal .report_time_option").html(html);



};
//初始化指标体系
UpLoadTemplate.initIndex = function (re) {
    var html = '';
    for(var i = 0; i < re.length; i++){
        var item = '<option value="'+re[i].id+'" data-code="'+re[i].code+'">'+re[i].name+'</option>';
        html += item;
    }
    $("#uploadTemplate_Modal .indexList").empty();
    $("#uploadTemplate_Modal .indexList").html(html);
    
};
//上传模板
UpLoadTemplate.uploadTemplate = function () {
    var files = $("#files").get(0).files[0];
    var year =$("#uploadTemplate_Modal .report_time_option  option:selected").val();
    var month = $("#uploadTemplate_Modal .report_time_month_option option:selected").val();
    var sysCode = $("#uploadTemplate_Modal .indexList option:selected").attr('data-code');
    var time = year+month;

    if(files==undefined|| files.name==""||files.name==null){
        alert("请先选择文件");
        return ;
    }
    if(!time){
        alert("请先选择时间");
        return ;
    }
    if(!sysCode){
        alert("请先选择指标");
        return ;
    }
    var fd = new FormData();
    fd.append('file',files);
    fd.append('year',time);
    fd.append('code',sysCode);
    fd.append('flag',"yes");

    var url = window.login_url.base_page_url+"/target/excel/upload";
    $.ajax({
        type: "POST",
        url: url,
        data:fd,
        cache: false,
        processData: false,
        contentType: false,
        success: function(re){
            if(re.status){
                alert(re.msg);
            }else{
                console.log('没有报告期年份');
            }
        },
        error:function (re) {
            console.log(re);
        }
    });


};